package com.zline.foodraise.ui.activity;

import android.content.Intent;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.JsAddrBean;
import com.zline.foodraise.entity.UserAddressBean;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.util.EmojiFilter;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.RegexUtils;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/8/8.
 * 添加和编辑地址
 */
@EActivity(R.layout.activity_add_edit_addr)
public class AddEditAddrActivity extends ZlineActivity {
    private static final String LOG_TAG = AddEditAddrActivity.class.getSimpleName();
    //标题 新增地址
    @StringRes(R.string.add_addr)
    String add_addr;
    //标题 修改地址
    @StringRes(R.string.modify_addr)
    String modify_addr;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;

    @ViewById(R.id.addr_name_et)
    EditText name_et;
    @ViewById(R.id.addr_phone_et)
    EditText phone_et;
    @ViewById(R.id.detail_addr_et)
    EditText detail_addr_et;
    JsAddrBean jsAddrBean;
    @ViewById(R.id.addr_city_county_hint_tv)
    TextView city_district_tv;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //添加、修改地址
    @Extra
    int flag;
    @Extra
    UserAddressBean userAddressBean;
    @Bean
    NetworkUtil networkUtil;

    @AfterViews
    void doSomeAfterView() {
        initView();
    }

    void initView() {
        if (networkUtil.isNetworkAvailable()) {
            if (flag == Constant.ADD_ADDR_FLAG) {
                title_tv.setText(add_addr);
            } else if (flag == Constant.MODIFY_ADDR_FLAG) {
                title_tv.setText(modify_addr);
                if (userAddressBean == null) return;
                name_et.setText(userAddressBean.getReceiverName());
                phone_et.setText(userAddressBean.getReceiverMobile());
                city_district_tv.setText(userAddressBean.getPreAddr() + userAddressBean.getSubAddr());
                detail_addr_et.setText(userAddressBean.getDetailAddr());
            }
        } else {
            TUtil.showShort(this, R.string.fail_load_data);
        }
    }


    @OnActivityResult(Constant.ADD_MODIFY_ADDR_REQUEST_CODE)
    void onActivityResult(int resultCode, Intent data, @OnActivityResult.Extra String value) {
        switch (resultCode) {
            case Constant.ADDR_SET_RESULT_CODE:
                Gson gson = new Gson();
                jsAddrBean = gson.fromJson(value, JsAddrBean.class);
                setCityAndDistrict(jsAddrBean);
                LUtil.i(LOG_TAG, "________JsAddrBean______bean____" + jsAddrBean.getCityId());
                break;
            default:
                break;
        }
    }


    //设置区县信息
    void setCityAndDistrict(JsAddrBean jsAddrBean) {
        city_district_tv.setText(jsAddrBean.getPreAddr());

    }


    //添加修改地址
    void addModifyAddr() {
        if (jsAddrBean == null && flag == Constant.ADD_ADDR_FLAG) {
            TUtil.showShort(this, R.string.wrong_delivery_addr);
            return;
        }
        String name = name_et.getText().toString();
        if (StringUtils.isBlank(name)) {
            TUtil.showShort(this, R.string.wrong_contact);
            return;
        }
        String phone = phone_et.getText().toString();
        phone = EmojiFilter.filterEmoji(phone);
        if (StringUtils.isBlank(phone) || !RegexUtils.checkMobile(phone)
                || !RegexUtils.checkPhone(phone)) {
            TUtil.showShort(this, R.string.wrong_phone);
            return;
        }

        String detailAddr = detail_addr_et.getText().toString();
        detailAddr = EmojiFilter.filterEmoji(detailAddr);
        if (StringUtils.isBlank(detailAddr)) {
            TUtil.showShort(this, R.string.wrong_detail_addr);
            return;
        }

        String preAddr = "";
        String subAddr = "";
        double lonPoint = 0;
        double latPoint = 0;
        long cityId = 0;
        if (flag == Constant.ADD_ADDR_FLAG) {
            preAddr = jsAddrBean.getPreAddr();
            subAddr = jsAddrBean.getSubAddr();
            lonPoint = jsAddrBean.getLonPoint();
            latPoint = jsAddrBean.getLatPoint();
            cityId = jsAddrBean.getCityId();
            if (networkUtil.isNetworkAvailable()) {
                showLoadingDialog();
                requestAddAddr(preAddr, subAddr, detailAddr, phone, name, lonPoint, latPoint, cityId);
            } else {
                TUtil.showShort(this, R.string.no_network);
            }

        } else {
            if (userAddressBean == null) return;
            long userAddrId = userAddressBean.getUserAddressId();
            if (jsAddrBean != null) {
                preAddr = jsAddrBean.getPreAddr();
                subAddr = jsAddrBean.getSubAddr();
                lonPoint = jsAddrBean.getLonPoint();
                latPoint = jsAddrBean.getLatPoint();
                cityId = jsAddrBean.getCityId();
            } else {
                preAddr = userAddressBean.getPreAddr();
                subAddr = userAddressBean.getSubAddr();
                lonPoint = userAddressBean.getLonPoint();
                latPoint = userAddressBean.getLatPoint();
                cityId = userAddressBean.getCityId();
            }

            if (networkUtil.isNetworkAvailable()) {
                showLoadingDialog();
                requestModifyAddr(userAddrId, preAddr, subAddr, detailAddr, phone, name, lonPoint, latPoint, cityId);
            } else {
                TUtil.showShort(this, R.string.no_network);
            }
        }


    }

    //请求添加收货地址
    void requestAddAddr(String preAddr, String subAddr, String detailAddr,
                        String mobile, String contact, double lonPoint, double latPoint, long cityId) {
        httpOperator.requestAddAddr(httpUtil, preAddr, subAddr, detailAddr,
                mobile, contact, lonPoint, latPoint, cityId, requestAddrHandler);
    }

    //请求修改收货地址
    void requestModifyAddr(long userAddrId, String preAddr, String subAddr, String detailAddr,
                           String mobile, String contact, double lonPoint, double latPoint, long cityId) {

        httpOperator.requestModifyAddr(httpUtil, userAddrId, preAddr, subAddr, detailAddr,
                mobile, contact, lonPoint, latPoint, cityId, requestAddrHandler);
    }


    //增加、修改收货地址回调
    AsyncHttpResponseHandler requestAddrHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestAddrHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        setResult();
                    } else {
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally {
                    dissLoadingDialog();
                }
            }
        }


        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dissLoadingDialog();
        }
    };


    void setResult() {
        Intent intent = new Intent();
        setResult(Constant.ADD_MODIFY_ADDR_RESULT_CODE, intent);
        finish();
    }


    @Click({R.id.app_common_header_left_icon_iv, R.id.addr_ok_btn,
            R.id.addr_city_county_hint_tv
    })
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.addr_ok_btn:
                addModifyAddr();
                break;
            case R.id.addr_city_county_hint_tv:
                SetAddrActivity_.intent(this).startForResult(Constant.ADD_MODIFY_ADDR_REQUEST_CODE);
                break;
            default:
                break;
        }
    }
}
